//
//  LTLshouYe.m
//  WeiBo
//
//  Created by Apple_Lzzy46 on 16/9/12.
//  Copyright © 2016年 LTL. All rights reserved.
//

#import "LTLshouYe.h"
#import "LTLButtonXiala.h"
#import "LTLBiaoTiCaiDan.h"
#import "LTLhomeModel.h"
#import "LTLOriginalMicro-blog.h"
#import "LTLframeModel.h"
#import <AVFoundation/AVFoundation.h>
//#import <AudioToolbox/AudioToolbox.h> 


@interface LTLshouYe ()
@property(nonatomic,assign)NSInteger ni;

@property(nonatomic ,strong)NSMutableArray *home;

@end

@implementation LTLshouYe
 #pragma mark -   初始化
-(NSMutableArray *)home
{
    if (_home == nil) {
        _home = [NSMutableArray array];
    }
    return _home;
}
///即将显示
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    //有文本
    //发送按钮可用
    [self.tableView.mj_header beginRefreshing];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];

//    self.view.backgroundColor              = [UIColor greenColor];
    //设置按钮
    [self setNnavigationItem];
    
//    self.navigationController.tabBarItem
    //注册图标提示
    UIUserNotificationSettings *seting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge categories:nil];
    
    [[UIApplication sharedApplication] registerUserNotificationSettings:seting];

    
}
//未读数据提示
-(void)Unread
{
    
//    //路径
//    NSString *path = [[NSBundle mainBundle] pathForResource:@"1710" ofType:@"wav"];
//    //声音
//    static SystemSoundID soundIDTest = 0;
//    
//    if (path) {
//        //在系统注册声音
//        AudioServicesCreateSystemSoundID( (__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundIDTest );
//    }

    //获取未读微博
    [LTLNetworkRequest unread_countSuccess:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject)
    {
        
    
        NSInteger num =[responseObject[@"status"] integerValue];
        
//        NSLog(@"%ld",(long)num);
        
        if (num != 0 && num != self.ni ) {
           //播放声音
//            AudioServicesPlaySystemSound( soundIDTest );
            [LTLSpeechTool creatSpeechWithSpeechText:[NSString stringWithFormat:@"李泰良提醒您有%ld条未读微博",num]];
            //图标提示
            self.navigationController.tabBarItem.badgeValue =[NSString stringWithFormat:@"%ld",num];
            //图标提示
            [UIApplication sharedApplication].applicationIconBadgeNumber = num;
            //取数
            self.ni = num;
            
        }
        //恢复
      else if (num == 0)
      {
          self.navigationController.tabBarItem.badgeValue = 0;
          [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
      }
        
    
    }];

//    self.navigationController.tabBarItem.badgeValue =[NSString stringWithFormat:@"%d",i];
//    [UIApplication sharedApplication].applicationIconBadgeNumber = i;
}

#pragma mark - Table view data source
/**
 *  组数
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
    return 1;
}
/**
 *  行数
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
    return self.home.count;
}
#pragma mark - cell 数据
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    /**
     *  创建cell
     */
    LTLOriginalMicro_blog *cell = [LTLOriginalMicro_blog initCell:tableView];
    
    LTLframeModel *row = self.home[indexPath.row];
    
    cell.model = row;
    ///设置点击不变色
    cell.selectionStyle                    = UITableViewCellSelectionStyleNone;
    return cell;

    }
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    LTLframeModel *model = self.home[indexPath.row];
    
    
    return (model.OriginalHeight + model.forwardHeight+model.DIHeight) ;
}
-(void)tableView:(UITableView *)tableView didUnhighlightRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
//    LTLhomeModel *row = self.home[indexPath.row];

}
#pragma mark - 刷新数据
/**
 *  刷新
 */
-(void)refresh
{
    //下拉刷新
    self.tableView.mj_header = [ MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        LTLframeModel  *firstObject = self.home.firstObject;
        
        
        [self dadtSince_id:[firstObject.model.idstr doubleValue] max_id:0 array:^(NSArray * _Nonnull homeModel) {
            
            //清除未读提示
            self.navigationController.tabBarItem.badgeValue = 0;
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            //数组位置
            NSRange range = NSMakeRange(0, homeModel.count);
            
            NSIndexSet *IndexSet = [NSIndexSet indexSetWithIndexesInRange:range];
            ////添加数组在头部
            [self.home insertObjects:homeModel atIndexes:IndexSet];
            //结束刷新状态
            [self.tableView.mj_header endRefreshing];
            [self shuaXinTiShi:homeModel.count];
            
        }];
    } ];
    //上拉刷新
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        
        LTLframeModel  *lastObject = self.home.lastObject;
        
        [self dadtSince_id:0 max_id:[lastObject.model.idstr doubleValue] array:^(NSArray * _Nonnull homeModel) {
            //添加数组在底部
            [self.home addObjectsFromArray:homeModel];
            //结束刷新状态
            [self.tableView.mj_footer endRefreshing];
        }];
        
        
    } ];
}
-(void)shuaXinTiShi:(NSInteger)cont
{
    ///提示文本
    UILabel *label = [[UILabel alloc]initText:[NSString stringWithFormat:@"获取了%ld条新微博!",(long)cont] font:[UIFont systemFontOfSize:18] color:[UIColor blackColor]];
    label.alpha = 0;
    if (cont == 0) {
        
        label.text = @"没有新微博!";
    }
    //背景颜色
    label.backgroundColor = [UIColor redColor];
    //高度
    label.highly = self.navigationController.navigationBar.highly;
    //宽度
    label.width = self.view.width;
    //添加
    [self.navigationController.view insertSubview:label belowSubview:self.navigationController.navigationBar];
    //动画
    [UIView animateWithDuration:1 animations:^{
        
        label.transform = CGAffineTransformMakeTranslation(0, self.navigationController.navigationBar.highly+20);
        label.alpha = 1;
        
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:1 delay:0.5f options:UIViewAnimationOptionLayoutSubviews animations:^{
            
            label.transform = CGAffineTransformIdentity;
            label.alpha = 0;
            
        } completion:^(BOOL finished) {
            //移除
            [label removeFromSuperview];
            
        }];
    }];
    
}
#pragma mark - 获取微博数据
-(void)dadtSince_id: (double) since_id  max_id: (double) max_id array:(void (^)(NSArray <LTLframeModel *>* _Nonnull homeModel))array
{
    if (max_id != 0) {
        max_id = max_id-1;
    }
    
    [LTLNetworkRequest statusWithParametersSince_id:since_id max_id:max_id arrya:^(NSArray<LTLframeModel *> * _Nullable arrya) {
        
        //传出模型数据数组
        array(arrya);
        [self.tableView reloadData];
    }];
    
}
#pragma mark -  设置初始化
//UI 控件
-(void)setNnavigationItem
{
    if (self.langView == NULL) {
        self.tableView.estimatedRowHeight = 200;
        //显示数据
        [self dadtSince_id:0 max_id:0 array:^(NSArray<LTLframeModel *> * _Nonnull homeModel) {
            //清除未读提示
            self.navigationController.tabBarItem.badgeValue = 0;
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            
            [self.home addObjectsFromArray:homeModel];
        }];
 

        /**
         修改返回按钮
         */
        UIBarButtonItem *back                  = [[UIBarButtonItem alloc]init];
        back.title                             = @"返回";
        self.navigationItem.backBarButtonItem  = back;
        // 右按钮
        self.navigationItem.leftBarButtonItem  = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"navigationbar_friendsearch"] landscapeImagePhone:[UIImage imageNamed:@"navigationbar_friendsearch_highlighted"] style:UIBarButtonItemStyleDone target:self action:nil];
        //左按钮
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"navigationbar_pop"] landscapeImagePhone:[UIImage imageNamed:@"navigationbar_pop_highlighted"] style:UIBarButtonItemStyleDone target:self action:nil];
        //创建标题按钮
        UIButton *button                       = [[UIButton alloc]init];
        //设置按钮图片
        [button setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
        
        //设置按钮文字
        [button setTitle: [LTLModel read].name forState:UIControlStateNormal];
//        [button setTitle: @"首页" forState:UIControlStateNormal];
        [button.titleLabel sizeToFit];
        
        //设置按钮文字颜色
        [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        //按钮图片内边距
        button.imageEdgeInsets                 = UIEdgeInsetsMake(0, button.titleLabel.bounds.size.width, 0, 0);
        //按钮标题内边距
        button.titleEdgeInsets                 = UIEdgeInsetsMake(0, -(button.currentImage.size.width+25) , 0, 0);
        //添加按钮方法
        [button addTarget:self action:@selector(xiaLaCaiDan:) forControlEvents:UIControlEventTouchUpInside];
//        button.imageView.backgroundColor = [UIColor redColor];
//        button.titleLabel.backgroundColor = [UIColor blueColor];
        //按钮大小
        [button sizeToFit];
//        button.width = 300;
        //添加按钮到导航栏中间
        self.navigationItem.titleView          = button;
        //添加刷新控件
        [self refresh];
        //开启刷新
        [self.tableView.mj_header beginRefreshing];
        
//        self.navigationController.tabBarItem
        NSTimer *mun = [NSTimer scheduledTimerWithTimeInterval:5  target:self selector:@selector(Unread) userInfo:nil repeats:YES];
        //定时刷新微博数据
        [[NSRunLoop mainRunLoop] addTimer:mun forMode:NSRunLoopCommonModes];
        
    }
    else
    {
    //访客视图方法
    [self.langView langTiter:nil imager:nil];
        
    }
    
}
/**
 *  标题按钮方法
 *
 *  @param Button 标题按钮
 */
-(void)xiaLaCaiDan : (UIButton *)Button
{
    //下拉菜单视图
    LTLBiaoTiCaiDan *table                 = [[LTLBiaoTiCaiDan alloc]init];
    //遮罩视图
    LTLButtonXiala *button                 = [LTLButtonXiala initButtonPiont:Button View:table];
    //显示遮罩视图并将下拉菜单视图添加到遮罩视图
    [button xianShiButton:Button];
}


@end
